﻿using System.Drawing;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.Globalization;

namespace Xacc
{
	public static class Utility
	{
		public static int GetFontHeight(string family, FontUnit fontsize)
		{
			GraphicsUnit gu = GraphicsUnit.Point;
			float fv = 8;

			switch (fontsize.Unit.Type) {
				case UnitType.Cm:
					gu = GraphicsUnit.Millimeter;
					fv = (float)fontsize.Unit.Value * 10;
					break;
				case UnitType.Inch:
					gu = GraphicsUnit.Inch;
					fv = (float)fontsize.Unit.Value;
					break;
				case UnitType.Mm:
					gu = GraphicsUnit.Millimeter;
					fv = (float)fontsize.Unit.Value;
					break;

				case UnitType.Pica:
					gu = GraphicsUnit.Point;
					fv = (float)fontsize.Unit.Value * 12;
					break;
				case UnitType.Pixel:
					gu = GraphicsUnit.Pixel;
					fv = (float)fontsize.Unit.Value;
					break;
				case UnitType.Point:
					gu = GraphicsUnit.Point;
					fv = (float)fontsize.Unit.Value;
					break;
				case UnitType.Em:
				case UnitType.Ex:
				case UnitType.Percentage:
				default:
					break;
			}

			using (Font fnt = new Font(family, fv, gu)) {
				int fh = fnt.Height;
				fh += (fh) % 2;
				return fh;
			}
		}

		public static string Res(this Control control, string resourceKey)
		{
			return control.Page.ClientScript.GetWebResourceUrl(control.GetType(), resourceKey);
		}

		public static string GetValueAsString(this PropertyDescriptor property, object source)
		{
			object _value = property.GetValue(source);
			return
				property.Converter.CanConvertTo(typeof(string))
					? (string)property.Converter.ConvertTo(null, CultureInfo.InvariantCulture, _value, typeof(string))
					: _value.ToString();
		}

		public static bool AreEqual(this PropertyDescriptor property, object source, string value)
		{
			return
				property.Converter.CanConvertFrom(typeof(string))
					&& property.GetValueFromString(value).Equals(property.GetValue(source))
					|| string.Equals(value, property.GetValueAsString(source));
		}

		public static object GetValueFromString(this PropertyDescriptor property, string @value)
		{
			return property.Converter.ConvertFrom(null, CultureInfo.InvariantCulture, value);
		}

		public static void SetValueFromString(this PropertyDescriptor property, object source, string value)
		{
			property.SetValue(source, property.GetValueFromString(value));
		}
	}
}
